var http = require('http'),
    qs = require("querystring"),
    multiparty = require('multiparty'),
    uuid = require('uuid'),
    upload = require('./upload').uploadFile,
    getEvent = require('./getNews'),
    pushEvent = require('./pushNews');

/**
 * pathName：路由地址
 * querys：参数
 */
http.createServer(async(req, res) => {

    // 设置跨域、header类型、请求方式
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type");
    res.setHeader("Content-Type", "application/json");

    let pathName = req.url.split('?')[0],
        querys = null,
        postData = '';

    req.on("data", function(postDataChunk) {
        postData += postDataChunk;
    });

    if (req.method === "GET") {
        querys = qs.parse(req.url.split('?')[1]);

        /**
         * 获取推荐列表
         */
        if (pathName == '/getHot') {
            try {
                let hotRes = await getEvent.getHot();
                res.write(JSON.stringify({
                    code: 200,
                    data: hotRes
                }))
            } catch (err) {
                res.write(JSON.stringify({
                    code: 500,
                    msg: '查询失败'
                }));
            }

            res.end();
        }

        /**
         * 获取类别列表
         */
        if (pathName == '/getCate') {
            try {
                let cateRes = await getEvent.getCate();
                res.write(JSON.stringify({
                    code: 200,
                    data: cateRes
                }))
            } catch (err) {
                res.write(JSON.stringify({
                    code: 500,
                    msg: '查询失败'
                }));
            }

            res.end();
        }

        /**
         * 根据id获取类别
         */
        if (pathName == '/getCateById') {
            try {
                let cateRes = await getEvent.getCateById(querys.id);
                res.write(JSON.stringify({
                    code: 200,
                    data: cateRes[0]
                }))
            } catch (err) {
                res.write(JSON.stringify({
                    code: 500,
                    msg: '查询失败'
                }));
            }

            res.end();
        }

        /**
         * 获取文章列表
         * category_id：类别id
         * id为空时全部查询
         */
        if (pathName == '/getArticleList') {
            try {
                let articleRes = await getEvent.getArticleListByCate(querys.category_id || '');
                res.write(JSON.stringify({
                    code: 200,
                    data: articleRes
                }))
            } catch (err) {
                res.write(JSON.stringify({
                    code: 500,
                    msg: '查询失败'
                }));
            }

            res.end();
        }
        /**
         * 获取文章内容
         * id：文章id
         */
        if (pathName == '/getArticleById') {
            try {
                let articleRes = await getEvent.getArticleById(querys.id);
                res.write(JSON.stringify({
                    code: 200,
                    data: articleRes[0]
                }))
            } catch (err) {
                res.write(JSON.stringify({
                    code: 500,
                    msg: '查询失败'
                }));
            }

            res.end();
        }
    }

    if (req.method === "POST") {
        /**
         * 上传图片
         */
        if (pathName == '/upload') {
            var filedata = null;
            var form = new multiparty.Form({
                uploadDir: '../upload'
            });
            form.parse(req);
            form.on('file', (name, file, ...rest) => {
                filedata = file;
            });
            form.on('close', async() => {
                let key = uuid.v1() + filedata.originalFilename,
                    localFile = filedata.path;
                let resl = null;
                try {
                    resl = await upload(key, localFile);
                    res.write(JSON.stringify(resl));
                } catch (err) {
                    res.write(JSON.stringify(resl));
                }
                res.end();
            });
        }

        /**
         * 插入文章
         */
        if (pathName == '/uploadArticle') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.insertArticle(uuid.v1(), querys.title, querys.cover_img, querys.content, querys.category_id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '添加成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '添加失败'
                    }))
                }
                res.end();
            });
        }

        /**
         * 插入类别
         */
        if (pathName == '/insertcate') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.insertCategory(uuid.v1(), querys.title, querys.cover_img);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '添加成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '添加失败'
                    }))
                }

                res.end();
            });
        }

        /**
         * 更新类别
         */
        if (pathName == '/editCate') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.editCate(querys.id, querys.title, querys.cover_img);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '添加成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '添加失败'
                    }))
                }

                res.end();
            });
        }

        /**
         * 删除类别
         */
        if (pathName == '/deleteCate') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.deleteCate(querys.id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '删除成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '删除失败'
                    }))
                }

                res.end();
            });
        }

        /**更新文章
         * id：文章id
         */
        if (pathName == '/editArticle') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.editArticle(querys.id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '修改成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '修改失败'
                    }))
                }
                res.end();
            });
        }

        /**
         * 删除文章
         * id：文章id
         */
        if (pathName == '/deleteArticle') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                console.log(querys);
                try {
                    let resl = await pushEvent.deleteArticle(querys.id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '修改成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '修改失败'
                    }))
                }
                res.end();
            });
        }

        /**
         * 插入推荐
         */
        if (pathName == '/addHot') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.addHot(querys.id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '添加成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '添加失败'
                    }))
                }
                res.end();
            });
        }

        /**
         * 取消推荐
         */
        if (pathName == '/removeHot') {
            req.on("end", async() => {
                querys = qs.parse(postData);
                try {
                    let resl = await pushEvent.removeHot(querys.id);
                    res.write(JSON.stringify({
                        code: 200,
                        msg: '添加成功'
                    }))
                } catch (err) {
                    res.write(JSON.stringify({
                        code: 500,
                        msg: '添加失败'
                    }))
                }
                res.end();
            });
        }
    }
}).listen(3000)
